<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { getProcessIOStats } from '@/api/process'
import ProcessTable from '@/components/ProcessTable.vue'
import ProcessSearch from '@/components/ProcessSearch.vue'
import ProcessPagination from '@/components/ProcessPagination.vue'
import type { ProcessIOStat } from '@/types/process'

const processIOStats = ref<ProcessIOStat[]>([])
const loading = ref<boolean>(true)
const error = ref<string | null>(null)

// 搜索相关
const searchQuery = ref<string>('')

// 分页相关
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)

// 排序相关
const sortField = ref<keyof ProcessIOStat | null>(null)
const sortOrder = ref<'asc' | 'desc'>('asc')

// 计算过滤后的数据
const filteredProcessIOStats = computed(() => {
  if (!searchQuery.value) {
    return processIOStats.value
  }

  const query = searchQuery.value.toLowerCase()
  return processIOStats.value.filter((process) => process.name.toLowerCase().includes(query))
})

// 计算排序后的数据
const sortedProcessIOStats = computed(() => {
  let data = [...filteredProcessIOStats.value]

  if (!sortField.value) {
    return data
  }

  return data.sort((a, b) => {
    const aValue = a[sortField.value!]
    const bValue = b[sortField.value!]

    let comparison = 0
    if (typeof aValue === 'string' && typeof bValue === 'string') {
      comparison = aValue.localeCompare(bValue)
    } else if (typeof aValue === 'number' && typeof bValue === 'number') {
      comparison = aValue - bValue
    } else {
      comparison = String(aValue).localeCompare(String(bValue))
    }

    return sortOrder.value === 'asc' ? comparison : -comparison
  })
})

// 计算当前页数据
const paginatedProcessIOStats = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return sortedProcessIOStats.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(sortedProcessIOStats.value.length / pageSize.value)
})

// 处理排序
const handleSort = (field: keyof ProcessIOStat) => {
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortField.value = field
    sortOrder.value = 'asc'
  }
}

// 处理页码变化
const handlePageChange = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 清空搜索
const clearSearch = () => {
  searchQuery.value = ''
  currentPage.value = 1
}

const fetchProcessIOStats = async () => {
  try {
    loading.value = true
    error.value = null
    processIOStats.value = await getProcessIOStats()
  } catch (err) {
    error.value = '获取进程IO统计信息失败'
    console.error(err)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchProcessIOStats()
})
</script>

<template>
  <div class="process-monitoring-container">
    <h2 class="glass-card-header">进程IO统计</h2>

    <ProcessSearch v-model="searchQuery" @clear="clearSearch" />

    <div v-if="loading" class="loading">加载中...</div>

    <div v-else-if="error" class="error">{{ error }}</div>

    <div v-else>
      <ProcessTable
        :processes="paginatedProcessIOStats"
        :sort-field="sortField"
        :sort-order="sortOrder"
        @sort="handleSort"
      />

      <ProcessPagination
        :current-page="currentPage"
        :total-pages="totalPages"
        :total-items="filteredProcessIOStats.length"
        :search-query="searchQuery"
        @page-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
@use '@/style/process-monitoring.scss';
</style>
